package com.xigege.nio.bufferAndChannel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannelCopyFile {
    public static void main(String[] args)throws IOException {
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {//循环读取

            //z这里有一个重要的操作，一定不能忘记
            /*public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }*/
            byteBuffer.clear();//清空buffer

            int read = fileChannel01.read(byteBuffer);
            if (read == -1) {//读取完毕
                break;
            }
            //将buffer中的数据写入到fileChannel02中 -- 2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }

        //关闭流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
